package edu.clarkson.ee368.spring2012.coreservices;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


@Stateless
public class DeviceManagerBean implements DeviceManager {
	
	@PersistenceContext
	private EntityManager em;

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void setDeviceOnAccount(long accountId, String c2dmRegistrationId) {
		
		Account account = em.find(AccountImpl.class, accountId);
		Device device = em.find(DeviceImpl.class, c2dmRegistrationId);
		if (device == null) {
			device = new DeviceImpl();
			device.setC2DMRegistrationId(c2dmRegistrationId);
			em.persist(device);
		}
		account.setDevice(device);
		em.flush();
	}

}
